package pw.goyd.game.handler.imp;

import pw.goyd.game.api.DBDone;
import pw.goyd.game.constant.setting.GameSetting;
import pw.goyd.game.handler.Handler;
import pw.goyd.game.logic.SetNameRequest;
import pw.goyd.game.logic.SetNameResponse;
import pw.goyd.game.manager.GameManager;
import pw.goyd.game.server.Log;
import pw.goyd.game.server.LoginList;
import pw.goyd.protocol.model.Response;
import pw.goyd.subscribe.PlayerCustomer;

/**
 * 设置名字
 * Created by StanWind on 2016/11/3.
 */
public class SETNAME extends Handler {
    @Override
    public void handle() {
        PlayerCustomer player = LoginList.getPlayer(ctx.getChannel().getId());

        if (player == null) {
            Log.getLogger().error("空指针--->ChannelID[" + ctx.getChannel().getId() + "]");
            return;
        }

        SetNameRequest setNameRequest = new SetNameRequest();
        setNameRequest.readFromBytes(request.getData());
        String nickname = setNameRequest.getNickname();
        Response response = new Response();
        SetNameResponse setNameResponse = new SetNameResponse();
        if (nickname.length() > GameSetting.NAME_MAX_LENGTH) {
            setNameResponse.setState(3);                                    //  名字过长
        } else if (DBDone.isNicknameExist(nickname)) {
            setNameResponse.setState(1);                                    //  名字已存在
        } else {
            if (player.getNickname() != null) {                             //  名字是否为空来判断是否是注册了的账号
                if (player.getDiamond() >= GameSetting.NAME_MONEY) {        //  钱足够改名
                    Log.getLogger().info("玩家[" + player.getNickname() + "] 更改昵称为[ " + nickname + " ]");
                    GameManager.sendAnnounceMsg("玩家[" + player.getNickname() + "]使用改头换面卡更改名字为[ " + nickname + " ]");
                    player.setNickname(nickname);
                    player.setDiamond(player.getDiamond() - GameSetting.NAME_MONEY);    //  不是第一次注册要扣钱改名
                    DBDone.updatePlayer(player);                            //  需要更改玩家信息 而不是
                    setNameResponse.setState(0);
                } else {
                    setNameResponse.setState(2);                            //  金币不足
                }
            } else {
                GameManager.sendAnnounceMsg("让我们欢迎[" + nickname + "]来到斗牛人生吧！");
                player.setNickname(nickname);
                DBDone.insertPlayer(player);                                //  第一次插入
                setNameResponse.setState(0);
            }


        }
        response.setCmd(CMD_SETNAME);
        response.setTime(0);
        response.setData(setNameResponse.getBytes());
        ctx.getChannel().write(response);
        player.sendPlayerInfo();
    }
}
